package com.example.supermarketwrok.service;

import com.example.supermarketwrok.model.Supermarket;
import com.example.supermarketwrok.repository.SupermarketRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SupermarketServiceImpl implements SupermarketService{
    @Autowired
    private SupermarketRepository supermarketRepository;

    @Override
    public List<Supermarket> getAllSupermarket(){
        return supermarketRepository.findAll();
    }
    @Override
    public void saveSupermarket(Supermarket supermarket){
        this.supermarketRepository.save(supermarket);
    }
    @Override
    public Supermarket getSupermarketById(long id){
        // 调用数据访问层查找指定ID的商品，返回Optional==（选择)对象
        Optional<Supermarket> optional = supermarketRepository.findById(id);
        Supermarket supermarket = null;
        // 如果存在指定id的商品
        if (optional.isPresent()) {
            // 从Optional对象中获取商品对象
            supermarket = optional.get();
        } else {
            // 否则抛出运行时异常
            throw new RuntimeException("找不到商品ID :: " + id);
        }
        return supermarket;
    }

    // 删除指定id的商品
    @Override
    public void deleteSupermarketById(long id){
        this.supermarketRepository.deleteById(id);
    }
    @Override
    public Page<Supermarket> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);

        return this.supermarketRepository.findAll(pageable);
    }
    @Override
    public List<Supermarket> findByGoodsName(String goodsName) {
        List<Supermarket> goodsNames = supermarketRepository.findAllByGoodsName(goodsName);
        return goodsNames;
    }
    @Override
    public void updateSupermarket(Supermarket supermarket) {
        supermarketRepository.save(supermarket);
    }
}
